# -*- coding: utf-8 -*-
#===============================================================================
# Koro Business Environment
# Copyright (C) 2008  Antonio Corroppoli
#
#This file is part of Koro BE.
# 
# Koro BE is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Koro BE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Koro BE; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#===============================================================================

'''
Created on 20/ago/2011

@author: antstud
'''
import wx
from koro.ui.wxgui.widgets import controls as co

class LookupAttr(object):
    def __init__(self):
        self._attr={}
    
    def set(self,pos,name,field):
        self._attr[pos]=(name,field)
        return self
    
    def get_field(self,pos):
        return self._attr[pos][1]
    
    def get_name(self,pos):
        return self._attr[pos][0]

#===============================================================================
# LookupPanel
#===============================================================================
class LookupPanel(wx.Panel):
    def __init__(self,*args,**kwargs):
        wx.Panel.__init__(self,*args,**kwargs)
        #self.SetInitialSize((600,450))
        self._attr=None
        self._layout()
        #self.SetMinSize((self.lista.GetSize().GetWidth()+20,500))
        
        self.ctrl.bind(wx.EVT_TEXT_ENTER, self.on_lookup)
    
    def _layout(self):
        mainsizer=wx.GridBagSizer(0,0)
        #orsizer=wx.BoxSizer()
        self.ctrl=co.LabelTextCtrl(self,label='',orientation=wx.VERTICAL,style=wx.PROCESS_ENTER)
        mainsizer.Add(self.ctrl,(0,0),flag=wx.ALL,border=10)
        self.lista=co.ListCtrl(self,size=(580,270))
        mainsizer.Add(self.lista,(1,0),flag=wx.EXPAND|wx.TOP|wx.BOTTOM,border=10)
        mainsizer.AddGrowableCol(0)
        mainsizer.AddGrowableRow(1)
        self.SetSizer(mainsizer)
        self.Fit()
        mainsizer.Layout()
    
    def _set_lookup_attr(self,attr):
        self._attr=attr
    
    def on_lookup(self,evt):
        pass
    
    def reset_focus(self):
        self.ctrl.set_focus()


#===============================================================================
# LookupClientiFornitoriPanel
#===============================================================================
class LookupClientiPanel(LookupPanel):
    def __init__(self,*args,**kwargs):
        LookupPanel.__init__(self,*args,**kwargs)
        self.ctrl.set_label('Ragione Sociale')
        self.lista.insert_columns((co.Column('ID',50,'ID'),
                                   co.Column('Ragione Sociale',320,'ragione_sociale'),
                                   co.Column('Città',160,'get_citta'),
                                   co.Column("Prov.",50,'get_provincia'),
                                   ))
        self.SetClientSize((self.lista.GetSize().GetWidth()+10,400))
        observer=wx.GetApp().get_observer()
        observer.set_context('CLIENTI')
        self.lista.load(observer.get_objects())
    
    def on_lookup(self,evt):
        print 'ciao mondo clienti'
        rag_soc=self.ctrl.get_value()
        args,kwargs=((),{})
        if rag_soc:
            kwargs={'ragione_sociale':rag_soc}
        self._carica_lista(*args,**kwargs)
    
    def _carica_lista(self,*args,**kwargs):
        observer=wx.GetApp().get_observer()
        observer.set_context('CLIENTI')
        self.lista.load(observer.lookup(*args,**kwargs))


#===============================================================================
# LookupClientiFornitoriPanel
#===============================================================================
class LookupFornitoriPanel(LookupPanel):
    def __init__(self,*args,**kwargs):
        LookupPanel.__init__(self,*args,**kwargs)
        self.ctrl.set_label('Ragione Sociale')
        self.lista.insert_columns((co.Column('ID',50,'ID'),
                                   co.Column('Ragione Sociale',320,'ragione_sociale'),
                                   co.Column('Città',160,'get_citta'),
                                   co.Column("Prov.",50,'get_provincia'),
                                   ))
        self.SetClientSize((self.lista.GetSize().GetWidth()+10,400))
        observer=wx.GetApp().get_observer()
        observer.set_context('FORNITORI')
        self.lista.load(observer.get_objects())        
    
    def on_lookup(self,evt):
        print 'ciao mondo fornitori'
        rag_soc=self.ctrl.get_value()
        args,kwargs=((),{})
        if rag_soc:
            kwargs={'ragione_sociale':rag_soc}
        self._carica_lista(*args,**kwargs)
    
    def _carica_lista(self,*args,**kwargs):
        observer=wx.GetApp().get_observer()
        observer.set_context('FORNITORI')
        self.lista.load(observer.lookup(*args,**kwargs))



#===============================================================================
# LookupProdottiPanel
#===============================================================================
class LookupProdottiPanel(LookupPanel):
    def __init__(self,*args,**kwargs):
        self.fornitore=kwargs.pop('fornitore',None)
        LookupPanel.__init__(self,*args,**kwargs)
        self._set_lookup_attr(LookupAttr().
                              set(0,'Codice a Barre','barcode').
                              set(1,'Codice Forn.','codice_prod_forn').
                              set(2,'ID','ID').
                              set(3,'Descrizione','descrizione')                              
                              )
        if self.is_vendita():
            self._set_lista_vendita()
        else:
            self._set_lista_acquisto()
        
        #self.SetClientSize((self.lista.GetSize().GetWidth()+100,400))
        self.SetInitialSize((self.lista.GetSize().GetWidth()+10,370))
        observer=wx.GetApp().get_observer()
        observer.set_context('PRODOTTI')
        args, kwargs = [], {}
        if not self.is_vendita():
            kwargs['con_magazzino'] = True
        if self.fornitore is not None:
            kwargs['fk_fornitore'] = self.fornitore.ID
        self.lista.load(observer.get_objects(*args,**kwargs))
#        if self.fornitore is None:
#            self.lista.load(observer.get_objects())
#        else:
#            self.lista.load(observer.get_objects(fk_fornitore=self.fornitore.ID))
    def _set_lista_acquisto(self):
        self.lista.insert_columns((co.Column('ID',50,'ID'),                                   
                                   co.Column('Descrizione',250,'descrizione'),
                                   co.Column('Codice Forn.',100,'get_codice_prod_forn'),
                                   co.Column("Fornitore Principale",180,'get_fornitore_principale_fmt'),
                                   co.Column("Prezzo Forn.",100,"get_prezzo_fornitore_principale_fmt",wx.LIST_FORMAT_RIGHT)
                                   ))
    
    def _set_lista_vendita(self):
        self.lista.insert_columns((co.Column('ID',50,'ID'),                                   
                                   co.Column('Descrizione',300,'descrizione'),
                                   co.Column("Fornitore Principale",180,'get_fornitore_principale_fmt'),
                                   co.Column("Prezzo",100,"get_prezzo_fmt",wx.LIST_FORMAT_RIGHT)
                                   ))  
    
    def _layout(self):
        sizer=wx.BoxSizer()
        mainsizer=wx.GridBagSizer()
        #orsizer=wx.BoxSizer()
        self.campo=co.KChoice(self,label='Cerca in',choices=['Codice a Barre','Codice Forn.','ID','Descrizione'],size=(130,-1),spacing=-1)
        self.campo.select(0)
        self.ctrl=co.LabelTextCtrl(self,label='',style=wx.PROCESS_ENTER,spacing=-1)        
        hsizer=wx.BoxSizer()
        hsizer.Add(self.campo,0)
        hsizer.Add(self.ctrl,0)#,flag=wx.ALL,border=10)
        mainsizer.Add(hsizer,(0,0),flag=wx.ALL,border=5)
        self.lista=co.ListCtrl(self,size=(680,270))
        mainsizer.Add(self.lista,(1,0),flag=wx.EXPAND|wx.BOTTOM,border=2)
        mainsizer.AddGrowableCol(0)
        mainsizer.AddGrowableRow(1)
        sizer.Add(mainsizer,1,wx.ALL,5)
        self.SetSizer(sizer)
        self.Layout()
        self.Fit()
        #mainsizer.Layout()
    
    def is_vendita(self):
        return self.Parent.get_opt() == co.VENDITA
    
    def on_lookup(self,evt):
        print 'ciao mondo prodotti'
        campo=self.campo.selection
        pattern=self.ctrl.get_value()
        observer=wx.GetApp().get_observer()
        observer.set_context('PRODOTTI')
        args,kwargs=((),{})
        lookup_func='lookup'
        if campo==0 and pattern:
            kwargs={'barcode':pattern}
        elif campo==1 and pattern:#TODO:codforn
            lookup_func='lookup_by_codforn'
            kwargs={'pattern':pattern}
        elif campo==2 and pattern:#ID
            kwargs={'ID':pattern}
        elif campo==3 and pattern:#descrizione
            kwargs={'descrizione':pattern}
            
        self._carica_lista(lookup_func,*args,**kwargs)
        if campo==0:
            self.lista.SetFocus()
            self.lista.Select(0, True)
        else:
            self.ctrl.set_focus()
    
    def _carica_lista(self,lookup_func,*args,**kwargs):
        observer=wx.GetApp().get_observer()
        observer.set_context('PRODOTTI')
        if self.fornitore is None:
            self.lista.load(getattr(observer,lookup_func)(*args,**kwargs))
        else:
            self.lista.load(getattr(observer,lookup_func)(fk_fornitore=self.fornitore.ID,*args,**kwargs))
            